package com.bulletelc.apollopre.module.deal.clearing;

import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.OrderDataBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2018/01/20
 * desc  : TODO
 */

public class ClearingPresenter extends BasePresenter<ClearingContract.View> implements ClearingContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void placeOrder(String json, String token) {
        placeOrderImp(json, token);
    }

    @Override
    public void checkAddress(int addressId) {
        checkAddressImp(addressId);
    }

    /**
     * 提交订单
     *
     * @param json
     * @param token
     */
    private void placeOrderImp(String json, String token) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_CHECKOUT_ORDER)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parsePlaceOrder(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorPlaceOrder(response.getException().toString());
                        }
                    }
                });
    }

    private void parsePlaceOrder(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    Gson gson = new Gson();
                    OrderDataBean orderDataBean = gson.fromJson(object.getJSONObject("data").toString(), OrderDataBean.class);
                    if (isViewAttached()) {
                        getView().onSuccessPlaceOrder(orderDataBean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailPlaceOrder(metaObj.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorPlaceOrder("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailPlaceOrder(response.body().toString());
            }
        }
    }

    /**
     * 检查地址是否可以下单
     */
    private void checkAddressImp(int id) {
        OkGo.<String>post(NetWorkPath.POST_CHECK_ADDRESS)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken())
                .params("address_id", id)
                .params("type", 1)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCheckAddress(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    private void parseCheckAddress(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    boolean b = object.getBoolean("data");
                    if (isViewAttached()) {
                        getView().onSuccessCheckAddress(b);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailCheckAddress(metaObj.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorCheckAddress("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailCheckAddress(response.body().toString());
            }
        }
    }

}
